<template>
  <div class="exam-list">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams" inline>
        <el-form-item label="考试标题">
          <el-input 
            v-model="queryParams.query" 
            placeholder="请输入考试标题" 
            clearable 
            @keyup.enter="fetchExams"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="草稿" value="DRAFT" />
            <el-option label="已发布" value="PUBLISHED" />
            <el-option label="进行中" value="ONGOING" />
            <el-option label="已结束" value="FINISHED" />
            <el-option label="已归档" value="ARCHIVED" />
          </el-select>
        </el-form-item>
        <el-form-item label="学科">
          <el-select v-model="queryParams.subjectId" placeholder="请选择学科" clearable style="width: 150px">
            <el-option 
              v-for="subject in subjects" 
              :key="subject.id" 
              :label="subject.name" 
              :value="subject.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchExams" icon="Search">搜索</el-button>
          <el-button @click="resetQuery" icon="Refresh">重置</el-button>
          <el-button type="success" @click="fetchExams" icon="RefreshRight">刷新</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>考试列表</span>
        </div>
      </template>
      
      <el-table 
        :data="exams" 
        style="width: 100%" 
        v-loading="loading"
        empty-text="暂无数据"
      >
        <el-table-column prop="title" label="考试标题" min-width="120" />
        <el-table-column prop="subjectName" label="学科" min-width="120" />
        <el-table-column prop="duration" label="考试时长" width="120" align="center" />
        <el-table-column prop="startTime" label="开始时间" width="180" align="center" />
        <el-table-column prop="endTime" label="结束时间" width="180" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusDisplayName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary"
              size="small" 
              v-if="hasPermission('exam:list:edit')"
              @click="handleEdit(scope.row)"
              icon="Edit"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              v-if="hasPermission('exam:list:delete')"
              @click="handleDelete(scope.row)"
              icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { examApi } from '@/api/exams'
import { subjectApi } from '@/api/subjects'
import type { Exam, PageResponse } from '@/types'
import { usePermission } from '@/composables/usePermission'

const { hasPermission } = usePermission()

const loading = ref(false)
const exams = ref<Exam[]>([])
const subjects = ref<{id: number, name: string}[]>([])

// 查询参数
const queryParams = reactive({
  query: '',
  status: '',
  subjectId: undefined as number | undefined
})

// 分页参数
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 获取学科列表
const fetchSubjects = async () => {
  try {
    const res = await subjectApi.getActiveSubjects()
    console.log('学科列表响应:', res)
    subjects.value = res.data.map(subject => ({ id: subject.id, name: subject.name }))
  } catch (error) {
    console.error('获取学科列表失败:', error)
    // 添加用户友好的错误提示
    ElMessage.error('获取学科列表失败，请稍后重试')
  }
}

// 获取考试列表
const fetchExams = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page - 1, // 后端页码从0开始
      size: pagination.size,
      query: queryParams.query || undefined,
      status: queryParams.status || undefined,
      subjectId: queryParams.subjectId || undefined
    }
    console.log('查询参数:', params)
    const res: PageResponse<Exam> = await examApi.getExams(params)
    console.log('考试列表响应:', res)
    exams.value = res.content
    pagination.total = res.totalElements
  } catch (error) {
    console.error('获取考试列表失败:', error)
    // 添加用户友好的错误提示
    ElMessage.error('获取考试列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  queryParams.query = ''
  queryParams.status = ''
  queryParams.subjectId = undefined
  pagination.page = 1
  fetchExams()
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pagination.size = val
  pagination.page = 1
  fetchExams()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  pagination.page = val
  fetchExams()
}

// 获取状态显示名称
const getStatusDisplayName = (status: string) => {
  const statusMap: Record<string, string> = {
    'DRAFT': '草稿',
    'PUBLISHED': '已发布',
    'ONGOING': '进行中',
    'FINISHED': '已结束',
    'ARCHIVED': '已归档'
  }
  return statusMap[status] || status
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    'DRAFT': '',
    'PUBLISHED': 'success',
    'ONGOING': 'warning',
    'FINISHED': 'info',
    'ARCHIVED': 'info'
  }
  return typeMap[status] || ''
}

const handleAdd = () => {
  console.log('创建考试')
}

const handleEdit = (row: Exam) => {
  console.log('编辑考试', row)
}

const handleDelete = (row: Exam) => {
  console.log('删除考试', row)
}

onMounted(() => {
  fetchExams()
  fetchSubjects()
})
</script>

<style scoped>
.exam-list {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>